package com.desire.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.desire.interceptor.CustomIdInterceptor;
import com.desire.snowflake.IdWorker;
import com.desire.interceptor.SnowFlakeInterceptor;
import com.desire.snowflake.SnowflakeIdWorker;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-11 周一 18:05
 * @since 17
 */
@Configuration
@MapperScan("com.desire.mapper")
@ComponentScan("com.desire.mapper")
@PropertySource("classpath:druid.properties")
public class MybatisConfig {
    @Value("${druid.driverClassName}")
    private String driverClassName;
    @Value("${druid.url}")
    private String url;
    @Value("${druid.username}")
    private String username;
    @Value("${druid.password}")
    private String password;

    @Primary
    @Bean(name = "ds", initMethod = "init", destroyMethod = "close")
    public DruidDataSource ds() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }

    @Primary
    @Bean(name = "sf")
    public SqlSessionFactoryBean sf(DruidDataSource ds) throws IOException {
        SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
        sf.setDataSource(ds);
        sf.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath*:mapper/*Mapper*.xml"));

        //添加插件plugin intercepter
        //sf.setPlugins(idGenerator());

        sf.setPlugins(sfi);
        //sf.setPlugins(idGenerator());



        // 扫描定义实体类别名：小写类名
        sf.setTypeAliasesPackage("com.desire.entity");
        return sf;
    }
    @Autowired
    private SnowFlakeInterceptor sfi;

    @Bean
    public SnowFlakeInterceptor sfi(){
        return new SnowFlakeInterceptor();
    }

    @Bean("idgenerator") @Primary
    public CustomIdInterceptor idGenerator(){
        return new CustomIdInterceptor();
    }

    @Bean @Primary
    public SnowflakeIdWorker snowflakeIdWorker() {
        //配置雪花算法的机器id和数据中心id
        return new SnowflakeIdWorker(1, 1);
    }



    @Bean("idw")
    public IdWorker idw(){
        return new IdWorker(1,1,2);
    }
}
